package edu.zcmu.seckill.service.impl;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.wf.captcha.ArithmeticCaptcha;
import edu.zcmu.seckill.response.R;
import edu.zcmu.seckill.service.VerifyService;
import edu.zcmu.seckill.utils.JwtUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.util.concurrent.TimeUnit;


@Slf4j
@Service
public class VerifyServiceImpl implements VerifyService {

    @Autowired
    RedisTemplate redisTemplate;

    @Autowired
    JwtUtil jwtUtil;

    /**
     * 发送验证码
     * @param request
     * @param response
     */
    @Override
    public void captcha(HttpServletRequest request, HttpServletResponse response) {
        //获取用户token
        String token = request.getHeader(jwtUtil.getHeader());
        DecodedJWT tokenInfo = jwtUtil.getTokenInfo(token);
        String uid = tokenInfo.getClaim("id").asString();  //获得token中携带的用户id

        ArithmeticCaptcha captcha = new ArithmeticCaptcha(130, 48);

        captcha.setLen(3);  // 几位数运算，默认是两位
        captcha.getArithmeticString();  // 获取运算的公式：3+2=?

        //把新验证码给放入,3分钟过期
        redisTemplate.opsForValue().set("VerifyCode:"+uid,captcha.text(),3, TimeUnit.MINUTES);

        ServletOutputStream outputStream = null;
        try {
            outputStream = response.getOutputStream();
        } catch (IOException e) {
            e.printStackTrace();
        }
        captcha.out(outputStream);  // 输出验证码
    }

    /**
     * 检查验证码
     * @param code
     * @param request
     * @return
     */
    @Override
    public R checkCaptcha(String code, HttpServletRequest request) {
        //获取用户token
        String token = request.getHeader(jwtUtil.getHeader());
        DecodedJWT tokenInfo = jwtUtil.getTokenInfo(token);
        String uid = tokenInfo.getClaim("id").asString();  //获得token中携带的用户id

        if (code==null||"".equals(code)){
            return R.error().data("验证码为空","0");//0为错误
        }
        String  verifyCode= (String) redisTemplate.opsForValue().get("VerifyCode:" + uid);
        if (code.equals(verifyCode)){
            return R.ok().data("验证码正确","1");//1为成功
        }
        return R.error().data("验证码错误","0");
    }
}
